<template>
    <!--  <enjoy-drawer :visible.sync="isShow" :title="headerTitle" @close="handleClose" append-to-body>-->
    <div class="app-container">
        <div class="container-header">
            <span class="header-left">
                {{headerTitle}}
            </span>
        </div>
        <el-form :model="dialogForm" :inline="true" size="small" :rules="rules" ref="detailForm" label-width="100px">
            <el-row>
                <el-col :span="8">
                    <!--            物料名称：-->
                    <el-form-item :label="$t('inspectionManagement.materialName')" prop="materialName" ref="materialName">
                        <el-select style="width:100%" v-model="dialogForm.materialName" :disabled="!!queryParams.groupId" filterable size="small" reserve-keyword :placeholder="$t('public.inputPl')">
                            <el-option @click.native="handleMaterialName(item)" v-for="item in materialOptions" :key="item.id" :label="item.materialName" :value="item.materialName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <!--            物料编号：-->
                    <el-form-item :label="$t('mrbForm.materialNo')" prop="materialCode">
                        <!-- <el-input  v-model="dialogForm.materialCode" :placeholder="$t('public.placeholder',{placeholder: '物料编号'})" clearable size="small" /> -->
                        <el-select style="width:100%" v-model="dialogForm.materialCode" :disabled="!!queryParams.groupId" filterable size="small" reserve-keyword :placeholder="$t('public.inputPl')">
                            <el-option @click.native="handleMaterialCode(item)" v-for="item in materialOptions" :key="item.id" :label="item.materialCode" :value="item.materialCode">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <!--            主工厂：-->
                    <el-form-item label="主工厂" prop="factory" ref="factoryName">

                        <el-select style="width:100%" @change="handleFactorySelect" v-model="dialogForm.factory" :disabled="!!queryParams.groupId" filterable size="small" reserve-keyword :placeholder="$t('public.inputPl')">
                            <el-option v-for="item in factoryOptions" :key="item.id" :label="item.factoryName" :value="item.factoryName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <!--            修正工厂：：-->
                    <el-form-item label="修正工厂" prop="correctionFactory" ref="correctionFactory">

                        <el-select style="width:100%" @change="handleCorrectionFactorySelect" v-model="dialogForm.correctionFactory" :disabled="!!queryParams.groupId" filterable size="small" reserve-keyword :placeholder="$t('public.inputPl')">
                            <el-option v-for="item in factoryOptions" :key="item.id" :label="item.factoryName" :value="item.factoryName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <!--            版本号：：：-->
                    <el-form-item :label="$t('inspectionManagement.version')" prop="version">
                        <el-input :disabled="true" v-model="dialogForm.version" :placeholder="$t('public.placeholder',{placeholder: $t('inspectionManagement.version')})" clearable size="small" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <!--            生效日期：：-->
                    <el-form-item :label="$t('inspectionManagement.effectDate')" prop="effectiveDate">
                        <el-date-picker style="width:215px" v-model="dialogForm.effectiveDate" disabled value-format="yyyy-MM-dd" type="date" :placeholder="$t('public.placeholder',{placeholder: $t('inspectionManagement.effectDate')})">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-divider v-if="type !=3"></el-divider>
            <el-row v-if="type !=3">
                <!--        检验项目名称-->
                <el-col :span="8">
                    <!--              检验项目名称-->
                    <el-form-item label="检验项目名称" prop="projectName" ref="projectName">
                        <el-select class="line_select" @change="handleProjectSelect" v-model="dialogForm.projectCode" filterable size="small" reserve-keyword :placeholder="$t('public.inputPl')">
                            <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.projectCode">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <!--        检验项目代码-->
                <el-col :span="8">
                    <!--              检验项目代码-->
                    <el-form-item label="检验项目代码" prop="projectCode">
                        <el-input :disabled="true" v-model="dialogForm.projectCode" placeholder="自动带入" clearable size="small" />
                    </el-form-item>
                </el-col>
                <el-col :span="8"></el-col>
            </el-row>
            <el-row v-if="type !=3">
                <!--        主工厂值-->
                <el-col :span="8">
                    <!--              主工厂值：-->
                    <el-form-item label="主工厂值" prop="aesc">
                        <el-input style="width:100%" v-model="dialogForm.aesc" type="number" clearable :placeholder="$t('public.placeholder',{placeholder: '主工厂值'})" @blur="handlerBlur('aesc')" />
                    </el-form-item>
                </el-col>
                <!--        修正工厂值-->
                <el-col :span="8">
                    <!--              修正工厂值：-->
                    <el-form-item label="修正工厂值" prop="supplierValue">
                        <el-input v-model="dialogForm.supplierValue" :placeholder="$t('public.placeholder',{placeholder: '修正工厂值'})" type="number" clearable @blur="handlerBlur('supplierValue')" />
                    </el-form-item>
                </el-col>
                <!--        GAP值-->
                <el-col :span="8">
                    <!--              GAP值：：-->
                    <el-form-item label="GAP值" prop="gap">
                        <el-input :disabled="true" clearable v-model="dialogForm.gap" placeholder="待计算" size="small" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="type !=3">
                <el-col :span="24" align="center">
                    <el-button type="primary" @click="submitForm" class="btn-save" :loading="loading" icon="el-icon-document" size="small">{{$t('public.save')}}</el-button>

                </el-col>
            </el-row>
        </el-form>

        <div class="body-info">
            <el-table max-height="350" border stripe v-loading="loading" :data="typeList">
                <!--          序号-->
                <el-table-column :label="$t('public.serialNum')" type="index" width="55" align="center" />
                <!--          检验项目代码-->
                <el-table-column label="检验项目代码" prop="projectCode" align="center">
                    <template slot-scope="scope">
                        {{  type == 1 ? (scope.row.projectCode || '自动带入') : scope.row.projectCode  }}
                    </template>
                </el-table-column>
                <!--          检验项目名称-->
                <el-table-column label="检验项目名称" prop="projectName" align="center">

                </el-table-column>

                <!--          主工厂值-->
                <el-table-column label="主工厂值" prop="aesc" align="center">
                    <template slot-scope="scope">
                        <el-input v-if="type!=='3'" type="number" v-model="scope.row.aesc" :placeholder="$t('public.placeholder',{placeholder: '主工厂值'})" size="small" @blur="handleTableCellBlur('aesc', scope.row)" />
                        <span v-else>{{scope.row.aesc}}</span>
                    </template>
                </el-table-column>

                <!--          修正工厂值-->
                <el-table-column label="修正工厂值" prop="supplierValue" align="center">
                    <template slot-scope="scope">
                        <el-input v-if="type!=='3'" type="number" v-model="scope.row.supplierValue" :placeholder="$t('public.placeholder',{placeholder: '修正工厂值'})" size="small" @blur="handleTableCellBlur('supplierValue',scope.row)" />
                        <span v-else>{{scope.row.supplierValue}}</span>
                    </template>

                </el-table-column>

                <!--          GAP-->
                <el-table-column label="GAP" prop="gap" align="center">
                    <template slot-scope="scope">
                        {{  type == 1 ? (scope.row.gap || '待计算') : scope.row.gap  }}
                    </template>
                </el-table-column>

                <el-table-column v-if="type !=3" :label="$t('public.opera')" fixed="right" align="center" width="160">
                    <template slot-scope="scope">
                        <div class="action-wrap">
                            <table-body-btn type="gwdelete" @click.native="handleRemove(scope.row)" />
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleClose" icon="el-icon-close" size="small">{{$t('public.close')}}</el-button>
            <!--      <el-button v-if="type!=3"  type="primary" @click="submitForm" :loading="loading" icon="el-icon-document" size="small">{{$t('public.submit')}}</el-button>-->

        </div>
        <!-- 新增 弹框 -->
        <!--    <dialog-gap :visible.sync="visible" v-model="form" :type="dialogType" @refresh="getList()"></dialog-gap>-->
    </div>
    <!--  </el-dialog>-->
    <!--  </enjoy-drawer>-->
</template>

<script>
import {listAllMaterial} from '@/api/basic/material'
import {listALLFactory} from '@/api/basic/factory'
import {listAllProject} from '@/api/basic/project'

import {addGap, delGap, getGapVersion, listGap, updateGap,} from '@/api/basic/gap'

export default {
    name: 'gap-detial',
    // components:{EnjoySelectUser,EnjoySelectDeptTree,FileUploadInput},
    dicts: [
        // 'NYIQC_STANDARD', //标准品 【是，否】
        // 'NYIQC_STATUS', //状态 【0 再用 1停用 2报废】
        // 'NYIQC_MSA_STATUS', //MSA状态 【0完成  1未开始  2进行中】
    ],
    components: {
        // DialogGap,
    },
    props: {
        value: {
            type: Object,
        },
        // visible:{
        //   type:Boolean,
        //   default:false
        // },
        // type:[String,Number] //1:新增  2：编辑 3：查看
    },
    watch: {
        value(val) {
            this.dialogForm = { ...val }
            if (val) {
                this.getList()
            }
        },
    },
    computed: {
        // isShow:{
        //   get(){return this.visible},
        //   set(){},
        // },
        headerTitle() {
            const { type } = this
            let title = ''
            if (type == 1) {
                title = '新增GAP'
            }
            if (type == 2) {
                title = '编辑GAP'
            }
            if (type == 3) {
                title = 'GAP详情'
            }
            return title
        },
    },
    data() {
        return {
            type: 1, //1:新增  2：编辑 3：查看
            visible: false,
            dialogType: 1,
            form: {},
            loading: false,
            fullscreen: false,
            deviceOptions: undefined,
            gapOptions: undefined,
            typeList: [],
            dialogForm: {
                effectiveDate: new Date(),
            },
            materialOptions: [],
            factoryOptions: [],
            projectOptions: [],
            correctionFactoryOptions: [],
            queryParams: {
                pageNum: 1,
                pageSize: 20,
                groupId: undefined,
            },
            total: 0,
            // 表单校验
            rules: {
                materialName: [
                    {
                        required: true,
                        message: this.$t('formValidation.materialNameCannotBeEmpty'),
                        trigger: 'change',
                    },
                ],
                materialCode: [
                    {
                        required: true,
                        message: '物料编号不能为空',
                        trigger: 'change',
                    },
                ],
                factory: [
                    {
                        required: true,
                        message: '主工厂不能为空',
                        trigger: 'blur',
                    },
                ],
                correctionFactory: [
                    {
                        required: true,
                        message: '修正工厂不能为空',
                        trigger: 'blur',
                    },
                ],
                projectName: [
                    {
                        required: true,
                        message: this.$t('formValidation.inspectionItemNameCannotBeEmpty'),
                        trigger: 'blur',
                    },
                ],
                aesc: [
                    {
                        required: true,
                        message: '主工厂值不能为空',
                        trigger: 'blur',
                    },
                ],
                supplierValue: [
                    {
                        required: true,
                        message: '修正工厂值不能为空',
                        trigger: 'blur',
                    },
                ],
            },
        }
    },
    mounted() {
        const { type, id } = this.$route.query
        if (type) {
            this.type = type
        }
        if (id) {
            this.queryParams.groupId = id
            this.getList()
        }
        this.materialRemoteMethod()
        this.factoryRemoteMethod()
        this.projectRemoteMethod()
    },
    methods: {
        handleTableCellBlur(key, row) {
            // aesc supplierValue
            if (row.aesc && row.supplierValue) {
                this.loading = true
                const aesc = parseFloat(row.aesc)
                const supplierValue = parseFloat(row.supplierValue)
                row[key] = parseFloat(row[key]).toFixed(2)
                const gap = (aesc - supplierValue).toFixed(2)
                updateGap({
                    groupId: row.groupId,
                    id: row.id,
                    aesc: row.aesc,
                    supplierValue: row.supplierValue,
                    gap,
                }).then((res) => {
                    this.loading = false
                    if (res.code == 200) {
                        this.getList()
                    }
                })
            }
        },
        handlerBlur(key) {
            const value = this.dialogForm[key]
            if (value) {
                this.dialogForm[key] = parseFloat(value).toFixed(2)
            }
            const { supplierValue, aesc } = this.dialogForm
            if (supplierValue && aesc) {
                this.dialogForm.gap = parseFloat(aesc - supplierValue).toFixed(
                    2
                )
            }
            this.$forceUpdate()
        },

        getList() {
            return listGap(this.queryParams).then((res) => {
                this.loading = false
                if (res.code == 200) {
                    this.typeList = res.rows
                    this.total = res.total
                    if (this.type != 1) {
                        const data = res.rows.length > 0 ? res.rows[0] : {}
                        this.dialogForm = {
                            ...data,
                            projectName: '',
                            projectCode: '',
                            aesc: '',
                            supplierValue: '',
                            gap: '',
                        }
                    }
                }
            })
        },
        /** 发起提交 */
        submitForm: function () {
            this.$refs.detailForm.validate((valid) => {
                if (valid) {
                    this.loading = true
                    addGap(this.dialogForm).then(
                        (res) => {
                            this.loading = false
                            if (res.code == 200) {
                                this.$emit('refresh')
                                this.$modal.msgSuccess('操作成功!')
                                this.queryParams.groupId = res.data
                                this.getList().then(() => {
                                    this.dialogForm.projectName = ''
                                    this.dialogForm.projectCode = ''
                                    this.dialogForm.aesc = ''
                                    this.dialogForm.supplierValue = ''
                                    this.dialogForm.gap = ''
                                })
                            } else {
                                this.$modal.msgError(res.msg)
                            }
                        },
                        () => {
                            this.loading = false
                        }
                    )
                }
            })
        },
        handleClose(done) {
            this.$router.push({ path: '/inspect/gap' })
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.resetForm('queryForm')
            this.handleQuery()
        },
        handleAdd() {
            // this.typeList.push({})
            this.form = {}
            this.dialogType = 1
            this.visible = true
        },
        handleRemove(row) {
            this.loading = true
            delGap(row.id).then((res) => {
                this.getList()
            })
        },
        getGapVersion() {
            const { materialCode, correctionFactory } = this.dialogForm
            if (materialCode && correctionFactory) {
                getGapVersion({ correctionFactory, materialCode }).then(
                    (res) => {
                        if (res.code == 200) {
                            this.dialogForm.version = res.msg
                            this.$forceUpdate()
                        }
                    }
                )
            }
        },
        // 物料名称 Begin
        materialRemoteMethod() {
            listAllMaterial({ materialName: '' }).then((res) => {
                this.materialOptions = res.data
            })
        },
        handleMaterialName(item) {
            console.log(item)
            this.$set(this.dialogForm, 'materialCode', item.materialCode)
            this.$refs.materialName.$emit('el.form.blur')
            this.getGapVersion()
        },
        handleMaterialCode(item) {
            this.$set(this.dialogForm, 'materialName', item.materialName)
            this.$refs.materialName.$emit('el.form.blur')
            this.getGapVersion()
        },
        handleMaterialBlur(e) {
            const { materialOptions, dialogForm } = this
            if (!materialOptions.includes(dialogForm.materialName)) {
                this.dialogForm.materialName = ''
            }
        },
        // 物料名称 End

        // 主工厂 Begin
        factoryRemoteMethod() {
            listALLFactory({ factoryName: '' }).then((res) => {
                this.factoryOptions = res.data
            })
        },
        handleFactorySelect(e) {
            this.$refs.factoryName.$emit('el.form.blur')
        },
        handleFactoryBlur(e) {
            const { factoryOptions, dialogForm } = this
            if (!factoryOptions.includes(dialogForm.factory)) {
                this.dialogForm.factory = ''
            }
        },
        // 主工厂 End

        // 修正工厂 Begin
        correctionFactoryRemoteMethod(val, cb) {
            listALLFactory({ factoryName: val }).then((res) => {
                this.correctionFactoryOptions = res.data.map(
                    (i) => i.factoryName
                )
                cb(res.data)
            })
        },
        handleCorrectionFactorySelect(e) {
            this.$refs.correctionFactory.$emit('el.form.blur')
            this.getGapVersion()
        },
        handleCorrectionFactoryBlur(e) {
            const { correctionFactoryOptions, dialogForm } = this
            if (!correctionFactoryOptions.includes(dialogForm.factoryName)) {
                this.dialogForm.correctionFactory = ''
            }
        },
        // 修正工厂 End

        // 检验项目 Begin
        projectRemoteMethod(e, cb) {
            listAllProject({ projectName: '' }).then((res) => {
                this.projectOptions = res.data
            })
        },
        handleProjectSelect(e) {
            this.projectOptions.forEach((element) => {
                if (element.projectCode === e) {
                    this.dialogForm.projectName = element.projectName
                }
            })
            this.$forceUpdate()
            this.$refs.projectName.$emit('el.form.blur')
        },
        // 检验项目 End
    },
}
</script>

<style scoped>
.app-container {
    padding: 0;
    background-color: white;
}
.container-header {
    /*float: left;*/
    padding-left: 15px;
    width: 100%;
    border-bottom: 1px solid #ededf2;
}
.header-left {
    /*float: left;*/
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    line-height: 40px;
    /*display: flex;*/
    justify-content: center;
    border-bottom: 2px solid #0b7be3;
}
.body-info {
    padding: 0 15px;
}
.dialog-footer {
    text-align: center;
    padding: 15px 0;
}
</style>
